// @ts-nocheck
import React, { useState, useCallback, useEffect } from 'react';
import { Timeline, message, Tooltip } from 'antd';
import { TRDefault, TRMessage } from '#/components';
import { TjTable } from '@/pages/ETrade/components';
import { useTablePipeline, features } from 'ali-react-table';
import { PageLoading } from '@/components/index.js';
import styles from './index.less';
import { tabTableColumns, tabTableDataSource } from '../../helper.js';
import { UpSquareOutlined, DownSquareOutlined } from '#/utils/antdIcons.js';
import InfiniteScroll from 'react-infinite-scroller/index.js';
import moment from 'moment';
import { logList } from '../../services.js';
import { HttpCode } from '#/utils/contacts.js';
import _ from 'lodash';
import { object } from 'prop-types';

let flag = false;
interface props {
  formValues: any[];
}
const HistoryShot = (props: props) => {
  const { formValues } = props;
  const [pageSize] = useState<number>(50),
    [loading, setLoading] = useState<boolean>(false),
    [currentPage, setCurrentPage] = useState<number>(1),
    [total, setTotal] = useState<number>(-1),
    [logArray, setLogArray] = useState<any>([]);

  useEffect(() => {
    getHistoryTableData();
  }, []);

  const getNewTableData = (data: any) => {
    return (data || []).map((t: any, i: number) => {
      return {
        id: logArray.length + i,
        expand: false,
        ...t,
      };
    });
  };

  const searchData = async (param: any, type = 0) => {
    if (flag) return;
    flag = true;
    if (total === logArray.length && !type) {
      message.warning('没有更多数据');
      return;
    }
    const res = await logList(param, formValues.marketId).catch();
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data) return;
      setTotal(res.data.total);
      const data = res.data;
      const _temp = getNewTableData(data.records);
      setLogArray(type ? _temp : logArray.concat(_temp));
      flag = false;
    }
  };

  const getHistoryTableData = async () => {
    flag = false;
    setLogArray([]);
    setTotal(-1);
    setLoading(true);
    setCurrentPage(1);

    const param = {
      provinceId: formValues.provinceId,
      stationIdList: formValues.stationIdList,
      startDate: formValues.startDate,
      endDate: formValues.endDate,
      currentPage: 1,
      pageSize: pageSize,
    };
    await searchData(param, 1);
    setLoading(false);
  };

  const loadMore = () => {
    if (flag) return;
    setCurrentPage(currentPage + 1);
    const param = {
      provinceId: formValues.provinceId,
      stationIdList: formValues.stationIdList,
      startDate: formValues.startDate,
      endDate: formValues.endDate,
      currentPage: currentPage + 1,
      pageSize: pageSize,
    };
    searchData(param);
  };

  // useCallback(() => {
  const getColumns = () => {
    return tabTableColumns(formValues.marketId).map((x) => {
      const { tooltip, ...column } = x;
      if (tooltip) {
        column.render = (value) => {
          const str = value || value === 0 ? value : '-';
          return tooltip && value ? (
            <Tooltip placement="top" title={str}>
              <div className={styles.textover}>{str}</div>
            </Tooltip>
          ) : (
            str
          );
        };
      }
      return column;
    });
  };
  // }, [tabTableColumns(formValues.marketId)]);

  const getColumns2 = () => {
    const newTabTableColumns = _.cloneDeep(tabTableColumns(formValues.marketId));

    newTabTableColumns.unshift(tabTableDataSource);
    return newTabTableColumns.map((x) => {
      const { tooltip, ...column } = x;
      if (tooltip) {
        column.render = (value) => {
          const str = value || value === 0 ? value : '-';
          return tooltip && value ? (
            <Tooltip placement="top" title={str}>
              <div className={styles.textover}>{str}</div>
            </Tooltip>
          ) : (
            str
          );
        };
      }
      return column;
    });
  };

  return (
    <div className={styles.container}>
      {loading ? (
        <PageLoading />
      ) : (
        <div className={styles.contentBox}>
          {logArray.length ? (
            <InfiniteScroll
              initialLoad={false}
              pageStart={0}
              loadMore={loadMore}
              hasMore={!loading && total !== logArray.length}
              useWindow={false}
              className={styles.scroll}
            >
              <Timeline
                style={{
                  width: '100%',
                  paddingLeft: 24,
                }}
              >
                {logArray.map((t: any, i: number) => (
                  <Timeline.Item
                    key={t.id}
                    className={`${styles.timeline}  ${i === 0 ? styles.current : ''}`}
                    color="#ACB1C1"
                  >
                    <div className={styles.top_date}>
                      <div className={styles.timeline_left}>
                        {moment(t.operationTime).format('YYYY.MM.DD HH:mm:ss')}
                        <span className={styles.unit}>{`${
                          t.operationFlag == '1'
                            ? '新增行'
                            : t.operationFlag == '2'
                            ? '编辑行'
                            : t.operationFlag == '3'
                            ? '删除行'
                            : t.operationFlag == '4'
                            ? '手动导入'
                            : '自动导入'
                        }`}</span>

                        {t.expand ? (
                          <UpSquareOutlined
                            style={{ color: 'var(--font-primary)', marginLeft: 12 }}
                            onClick={() => {
                              setLogArray(
                                logArray.map((_t: any, _i: number) => {
                                  if (_i === i) {
                                    _t.expand = false;
                                  }
                                  return _t;
                                }),
                              );
                            }}
                          />
                        ) : (
                          <DownSquareOutlined
                            style={{ color: 'var(--font-primary)', marginLeft: 12 }}
                            onClick={() => {
                              setLogArray(
                                logArray.map((_t: any, _i: number) => {
                                  if (_i === i) {
                                    _t.expand = true;
                                  }
                                  return _t;
                                }),
                              );
                            }}
                          />
                        )}
                      </div>
                      <div className={styles.timeline_right}>
                        操作人：
                        <div className={styles.name}>{t.operationUserName}</div>
                      </div>
                    </div>

                    {t.expand && t.operationContent ? (
                      <>
                        <div className={styles.content}>
                          {/* 2：编辑  |  1、3：新增、删除  | 其他：手动、自动导入 */}
                          {t.operationFlag === '2' ? (
                            <>
                              <div className={styles.itemBox}>
                                {Object.values(getColumns2()).map((_t: any, _i: number) => {
                                  return (
                                    <div className={styles.item2} key={_i}>
                                      <div className={styles.top}>{_t.name}</div>
                                      {t?.operationContent?.[0] &&
                                        Object.keys(t?.operationContent[0])?.map((key: any) => {
                                          if (key === _t.code) {
                                            return (
                                              <Tooltip
                                                placement="top"
                                                title={t.operationContent[0][key]}
                                              >
                                                <div className={styles.bottom}>
                                                  {t.operationContent[0][key] !== null
                                                    ? t.operationContent[0][key].toString().length >
                                                      6
                                                      ? t.operationContent[0][key]
                                                          .toString()
                                                          .slice(0, 6) + '...'
                                                      : t.operationContent[0][key].toString()
                                                    : '-'}
                                                </div>
                                              </Tooltip>
                                            );
                                          }
                                        })}
                                      {t?.operationContent?.[1] &&
                                        Object.keys(t?.operationContent[1])?.map((key: any) => {
                                          if (key === _t.code) {
                                            return (
                                              <Tooltip
                                                placement="top"
                                                title={t.operationContent[1][key]}
                                              >
                                                <div className={styles.bottom}>
                                                  {t.operationContent[1][key] !== null
                                                    ? t.operationContent[1][key].toString().length >
                                                      6
                                                      ? t.operationContent[1][key]
                                                          .toString()
                                                          .slice(0, 6) + '...'
                                                      : t.operationContent[1][key].toString()
                                                    : '-'}
                                                </div>
                                              </Tooltip>
                                            );
                                          }
                                        })}
                                    </div>
                                  );
                                })}
                              </div>
                            </>
                          ) : t.operationFlag === '1' || t.operationFlag === '3' ? (
                            <>
                              <div className={styles.itemBox}>
                                {Object.values(getColumns()).map((_t: any, _i: number) => {
                                  return (
                                    <div className={styles.item1} key={_i}>
                                      <div className={styles.top}>{_t.name}</div>
                                      {t?.operationContent?.[0] &&
                                        Object.keys(t?.operationContent[0])?.map((key: any) => {
                                          if (key === _t.code) {
                                            return (
                                              <Tooltip
                                                placement="top"
                                                title={t.operationContent[0][key]}
                                              >
                                                <div className={styles.bottom}>
                                                  {t.operationContent[0][key] !== null
                                                    ? t.operationContent[0][key].toString().length >
                                                      6
                                                      ? t.operationContent[0][key]
                                                          .toString()
                                                          .slice(0, 6) + '...'
                                                      : t.operationContent[0][key].toString()
                                                    : '-'}
                                                </div>
                                              </Tooltip>
                                            );
                                          }
                                        })}
                                    </div>
                                  );
                                })}
                              </div>
                            </>
                          ) : (
                            <>
                              <div className={styles.fileNameBox}>
                                {'数据表名: ' + t.operationContent[0].fileName}
                              </div>
                            </>
                          )}
                        </div>
                      </>
                    ) : (
                      ''
                    )}
                  </Timeline.Item>
                ))}
              </Timeline>
            </InfiniteScroll>
          ) : (
            <TRDefault type="empty" />
          )}
        </div>
      )}
    </div>
  );
};
export default HistoryShot;
